package io.chance.receiverlei.schedule;

import io.chance.receiverlei.db.DbHelper;
import io.chance.receiverlei.db.DbManager;
import io.chance.receiverlei.db.model.BdMoRt;
import io.chance.receiverlei.db.model.DeviceKv4301;
import lrq.common.MyLog;
import lrq.common.PropertiesUnit;
import lrq.data.DataTable;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FixDataJob implements Job {
    Logger log;

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {

        if (log == null) {
            log = MyLog.getLogger(getClass().getSimpleName());
        }
        log.info("开始数据修补");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.SECOND, 0);
        Timestamp now = new Timestamp(cal.getTime().getTime());

        try {
            String sql = "select SITE_ID from bd_mo_rt_single t group by t.SITE_ID";

            DataTable table = DbManager.getDbExecuter().executeQuery(sql);
            for (int i = 0; i < table.getRecordCount(); i++) {
                String siteId = table.getString(i, "SITE_ID");
                sql = "select * from bd_mo_rt_single t where t.SITE_ID='" + siteId + "' order by t.DATATIME";
                DataTable dataTable = DbManager.getDbExecuter().executeQuery(sql);
                if (dataTable.getRecordCount() == 0) {
                    continue;
                }
                List<BdMoRt> moRts = new ArrayList<>(dataTable.getRecordCount());
                for (int j = 0; j < dataTable.getRecordCount(); j++) {
                    Date date = dataTable.getDate(j, "DATATIME");
                    if (date != null && now.getTime() - date.getTime() < 600000) {//更新时间小于3分钟的才算进实时
                        BdMoRt bdMoRt = new BdMoRt().setID(UUID.randomUUID().toString()).setSITE_ID(siteId)
                            .setPARAMETER(dataTable.getString(j, "PARAMETER"))
                            .setVALUE(dataTable.getString(j, "VALUE"))
                            .setDATATIME(now).setCREATETIME(now);
                        moRts.add(bdMoRt);
                    }
                }
                DbManager.getDbExecuter().Create(moRts);
                log.info(siteId + "实时数据修补完成" + moRts.size());

                transRt2DeviceKvAndInsert(moRts);
            }
        }
        catch (Exception e) {
            log.error("修补数据出错", e);
        }
    }

    private HashMap<String, String> pollToTrans01 = PropertiesUnit.getMap("pollToTrans01");
    private int deviceType = PropertiesUnit.getInt("deviceType") < 0 ? 0 : PropertiesUnit.getInt("deviceType");
    private String address = PropertiesUnit.getValue("address") == null || PropertiesUnit.getValue("address").equals("") ? "1" : PropertiesUnit.getValue("address");

    public void transRt2DeviceKvAndInsert(List<BdMoRt> models) {
        if (models.size() > 0) {
            String tableName = null;
            try {
                DeviceKv4301 device = new DeviceKv4301().setITEMID(UUID.randomUUID().toString()).setDEVICETYPE(deviceType).setONLINEFLAG(0).setADDRESS(address)
                    .setGATEWAY("1001" + String.format("%03d", Integer.valueOf(models.get(0).getSITE_ID()))).setCREATETIME(models.get(0).getCREATETIME()).setINSTPOS("");
                LocalDateTime time = LocalDateTime.ofInstant(models.get(0).getCREATETIME().toInstant(), ZoneId.systemDefault());
                if (time.getDayOfMonth() < 11) {
                    device.setTableName("devicekv4301" + (time.getYear() - 2000) + String.format("%02d", time.getMonthValue()) + "0");
                }
                else if (time.getDayOfMonth() > 20) {
                    device.setTableName("devicekv4301" + (time.getYear() - 2000) + String.format("%02d", time.getMonthValue()) + "2");
                }
                else {
                    device.setTableName("devicekv4301" + (time.getYear() - 2000) + String.format("%02d", time.getMonthValue()) + "1");
                }
                tableName = device.getTableName();
                DbHelper.createDataTableIfNotExist(device.getTableName());

                for (BdMoRt rt : models) {
                    if (rt.getPARAMETER().equals(pollToTrans01.get("1"))) {
                        device.setLJNUM(Integer.parseInt(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("2.1"))) {
                        device.setAXDY(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("2.2"))) {
                        device.setBXDY(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("2.3"))) {
                        device.setCXDY(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("3.1"))) {
                        device.setAXDL(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("3.2"))) {
                        device.setBXDL(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("3.3"))) {
                        device.setCXDL(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("4"))) {
                        String ss = String.format("%04d", Integer.valueOf(Integer.toBinaryString(Integer.valueOf(rt.getVALUE()))));
                        device.setAIRSWITCH(1 - Integer.valueOf(ss.charAt(1) + ""));
                        device.setSPDJD(1 - Integer.valueOf(ss.charAt(2) + ""));
                        device.setSPD(1 - Integer.valueOf(ss.charAt(3) + ""));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("5"))) {
                        device.setTEMPERATURE2(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("6.1"))) {
                        device.setTEMPERATURE1(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("6.2"))) {
                        device.setHUMIDITY1(Double.valueOf(rt.getVALUE()));
                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("7"))) {

                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("8"))) {

                    }
                    else if (rt.getPARAMETER().equals(pollToTrans01.get("14"))) {//雷击时间 4,*,date;
                        device.setLJTIME(getLJTime(rt.getVALUE()));
                    }
                }
//                if(device.getLJTIME()==null) device.setLJTIME(new Timestamp(LocalDateTime.MIN.toEpochSecond(ZoneOffset.ofHours(8))*1000));
                if (device.getLJTIME() == null) {
                    device.setLJTIME(new Timestamp(0));
                }
                DbManager.getDbExecuter().Create(device);
                log.info(device.getGATEWAY() + "devicekv数据更新完成");
            }
            catch (Exception e) {
                log.error(tableName, e);
            }
        }
    }

    private final Pattern pattern = Pattern.compile(";4,\\d+,(.*?),\\d+;");
    private final Pattern pattern1 = Pattern.compile("^4,\\d+,(.*?),\\d+;");
    private final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    private Timestamp getLJTime(String text) {
        Timestamp timestamp = null;
        try {
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                timestamp = new Timestamp(LocalDateTime.parse(matcher.group(1), DTF).toEpochSecond(ZoneOffset.ofHours(8)) * 1000);
            }
            else {
                matcher = pattern1.matcher(text);
                if (matcher.find()) {
                    timestamp = new Timestamp(LocalDateTime.parse(matcher.group(1), DTF).toEpochSecond(ZoneOffset.ofHours(8)) * 1000);
                }
            }
        }
        catch (Exception e) {
            log.error(text, e);
        }
        return timestamp;
    }
}
